package com.competitions.videoedithelper.config;

import com.auth0.jwt.JWT;
import com.competitions.videoedithelper.entity.ResponseModel;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mapler
 */
public class ReqInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到请求头
        String options = "OPTIONS";
        if(options.equals(request.getMethod())){
            //在拦截器中设置允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers","*");
            response.setHeader("Access-Control-Allow-Methods","*");
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setHeader("Access-Control-Max-Age","3600");
            return true;
        }
        //获得token
        String authorization = request.getHeader("Authorization");
        String token = null;
        if(authorization != null) {
            token = authorization.substring(7);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //如果token没有则返回
        if(token==null || token.length()==0){
            JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "无token，不允许访问！").toString());
            response.getWriter().append(jsonObject.toString()).flush();
            return false;
        }
        else {
            try{
                Long currentTime = System.currentTimeMillis();
                Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
                Long expTime = JWT.decode(token).getClaim("exptime").asLong();
                if(currentTime - generateTime > expTime) {
                    JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(320, "token过期，请重新登录！").toString());
                    response.getWriter().append(jsonObject.toString()).flush();
                    return false;
                }
            }catch (Exception e){
                e.printStackTrace();
                //验证失败
                JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(330, "token无效，不允许访问！").toString());
                response.getWriter().append(jsonObject.toString()).flush();
                return false;
            }
        }
        return true;
    }

}
